from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt
import json

@csrf_exempt
def api_login(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data.get('username')
            password = data.get('password')
            remember_me = data.get('remember_me', False)
            
            user = authenticate(username=username, password=password)
            
            if user is not None:
                login(request, user)
                if not remember_me:
                    # 设置session在浏览器关闭时过期
                    request.session.set_expiry(0)
                return JsonResponse({
                    'status': 'success', 
                    'message': '登录成功',
                    'user': {
                        'id': user.id,
                        'username': user.username,
                        'email': user.email
                    }
                })
            else:
                return JsonResponse({
                    'status': 'error',
                    'message': '用户名或密码错误，请重试'
                }, status=400)
        except json.JSONDecodeError:
            return JsonResponse({
                'status': 'error',
                'message': '无效的请求数据'
            }, status=400)
        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'message': '服务器错误，请稍后再试'
            }, status=500)
    return JsonResponse({
        'status': 'error', 
        'message': '不支持的请求方法'
    }, status=405)


@csrf_exempt
def api_logout(request):
    logout(request)
    return JsonResponse({'status': 'success', 'message': '登出成功'})

def check_auth(request):
    if request.user.is_authenticated:
        return JsonResponse({
            'status': 'success',
            'isAuthenticated': True,
            'user': {
                'id': request.user.id,
                'username': request.user.username
            }
        })
    return JsonResponse({
        'status': 'success',
        'isAuthenticated': False
    })